package no.ntnu.idi.deid.patternmatching.search.dictionary.medicalcodes;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;

import no.ntnu.idi.deid.config.FilePaths;
import no.ntnu.idi.deid.documentunits.Token;
import no.ntnu.idi.deid.searchresultunits.CategoryTag;
import no.ntnu.idi.deid.searchresultunits.Tag;

public class MESH_Codes {
	
	
	private static Map<String,String> meshCodes;
	
//	private static MESH_Codes instance;
	
	protected MESH_Codes() {
		if (meshCodes == null){
			makeMeshCodesSet();
		}
	}
	
	
	private void readAndHandleLine(String line){
		String code = line.split(" ")[0];
		String desc = line.substring(line.indexOf(" "));
		meshCodes.put(code.trim(), desc.trim());
	}
	
	private void makeMeshCodesSet(){
		meshCodes = new HashMap<String, String>();
		Scanner sc = null;
		try {
			sc = new Scanner(new File(FilePaths.getMeshCodesPath()));
			while (sc.hasNext()) {
				String line = sc.nextLine();
				readAndHandleLine(line.trim());
			}
			sc.close();
		} catch (FileNotFoundException e) {
			if(sc!=null){sc.close();}
			e.printStackTrace();
		}

	}
	
	public static CategoryTag searchMeshCodes(Token token) {
		new MESH_Codes();
		String str = token.getStripped();
		String se = meshCodes.get(str);
		if(se!=null){
			CategoryTag tag = new CategoryTag(Tag.MESH);
			tag.setValues(str, se);
			return tag;
		}
		return null;
	}
	
	public static CategoryTag searchExactDescription(String str) {
		new MESH_Codes();
		Iterator<Entry<String, String>> it = meshCodes.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			if(entry.getValue().equals(str.trim())){
				CategoryTag tag = new CategoryTag(Tag.MESH);
				tag.setValues(entry.getKey(), entry.getValue());
				return tag;
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		Token t = new Token(654641, "D001208");
		CategoryTag tag = searchMeshCodes(t);
		System.out.println(tag.getDescription());
	}
}
